﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace Demo.Controllers
{
    public class AttachmentController : Controller
    {
        //用户头像目录
        private readonly string _dirOfProfilePhoto = "ProfilePhoto";
        //文件上传目录
        private readonly string _dirOfUpload = "Upload";

        private IWebHostEnvironment _hostingEnv;

     

        public AttachmentController( IWebHostEnvironment env, ILogger<AttachmentController> logger)
        {
            _hostingEnv = env;
       
        }

        /// <summary>
        /// 上传附件（只要符合附件文件类型的文件就都可以上传） 这是新增加的方法
        /// </summary>
        /// <param name="id"></param>
        /// <param name="name"></param>
        /// <param name="uploadType"></param>
        /// <param name="lastModifiedDate"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public async Task<IActionResult> UploadFile(string id, string name, string lastModifiedDate, int size)
        {
            int uploadType = 9; //定义类型为其它文件

            if (Request.Form.Files.Count == 0)
            {
                return Json(new
                {
                    success = false,
                    id = "id",
                    error = new
                    {
                        code = 102,
                        message = "没有找到上传的文件！"
                    }
                });
            }
            IFormFile formFile = Request.Form.Files[0];

            //获取要保存到的位置和名称
            string oldName = Path.GetFileNameWithoutExtension(formFile.FileName); //获取上传的文件名（不含扩展名）
            string fileExt = Path.GetExtension(formFile.FileName);
            string hostPath = "";
            string filePath = GetUploadDir(uploadType, "", out hostPath);
            string fileName = Guid.NewGuid().ToString("N");
            string filePathName = Path.Combine(filePath + fileName + fileExt);

            //判断附件文件类型是否正确

            //string ext = _uploadService.GetByKey("FileExt").OptionValue;

            string ext = "*.jpg,*.png,*.doc,*.docx";

            //为了方便查询，加入,号。处理后都按"doc," 这样的文本查询
            ext = ext.Trim() + ",";
            string fileExtNoDot = fileExt;

            //加入，号以方便匹配查询
            if (fileExt.Length > 2)
            {
                fileExtNoDot = fileExtNoDot.Substring(1) + ",";
            }

            //_logger.LogError($"FileExt:{ext},fielExt:{fileExtNoDot}");

            if (ext.IndexOf(fileExtNoDot) < 0)
            {
                return Json(new
                {
                    success = false,
                    id = "id",
                    error = new
                    {
                        code = 102,
                        message = "系统不支持上传此类型的文件！"
                    }
                });
            }

            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }


            using (var stream = new FileStream(filePathName, FileMode.Create))
            {
                await formFile.CopyToAsync(stream);
                //stream.Flush();
            }


            return Json(new
            {
                success = true,
                id = id,
                filePath = $"{hostPath}{fileName}{fileExt}",
                extName = fileExt,
                oldName = oldName
            });
        }


        #region 私有方法

        /// <summary>
        /// 获得上传文件要保存到的目录
        /// </summary>
        /// <param name="uploadType">上传文件类型 1普通图片 2用户头像 4项目相关文件 9相关文件</param>
        /// <returns></returns>
        private string GetUploadDir(int uploadType, string subDirName, out string hostPath)
        {

            string filePath = string.Empty;
            string subDir = DateTime.Now.ToString("yyyyMM");
            switch (uploadType)
            {
                case 1:
                    filePath = $"{_hostingEnv.WebRootPath}/{_dirOfUpload}/images/{subDir}/";
                    hostPath = $"/{_dirOfUpload}/images/{subDir}/";
                    break;
                case 2:
                    filePath = $"{_hostingEnv.WebRootPath}/{_dirOfProfilePhoto}/";
                    hostPath = $"/{_dirOfProfilePhoto}/";
                    break;
                case 4: //项目相关文件 保存目录可能为： upload/项目名称/
                    filePath = $"{_hostingEnv.WebRootPath}/{_dirOfUpload}/project/{subDir}/{subDirName}/";
                    hostPath = $"/{_dirOfUpload}/project/{subDir}/{subDirName}/";
                    break;
                default:
                    filePath = $"{_hostingEnv.WebRootPath}/{_dirOfUpload}/files/{subDir}/";
                    hostPath = $"/{_dirOfUpload}/files/{subDir}/";
                    break;
            }


            return filePath;
        }

        #endregion
    }
}
